package com.whmskj.xjlhbc.mobile.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhbc.domain.Jx05dStaffIncentiveAndSanctionLo;
import com.whmskj.xjlhbc.domain.PersonnelManagementDataSheets;
import com.whmskj.xjlhbc.dto.JcQueryDto;
import com.whmskj.xjlhbc.mapper.Bcry11ygsqbdMapper;
import com.whmskj.xjlhbc.service.IJx05dStaffIncentiveAndSanctionLoService;
import com.whmskj.xjlhbc.service.IPersonnelManagementDataSheetsService;
import com.whmskj.xjlhbc.vo.ApproveRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whmskj.xjlhbc.mapper.CorpMemberMapper;
import com.whmskj.xjlhbc.domain.CorpMember;
import org.springframework.util.StringUtils;

@RestController
@Tag(name = "奖惩记录", description = "奖惩记录")
@RequestMapping("/staffIncentiveAndSanctionLo")
@SaIgnore
@Slf4j
public class JcController {

    @Autowired
    private IJx05dStaffIncentiveAndSanctionLoService service;

    @Autowired
    private IPersonnelManagementDataSheetsService personnelManagementDataSheetsService;

    @Autowired
    private CorpMemberMapper corpMemberMapper;

    @Autowired
    private Bcry11ygsqbdMapper bcry11ygsqbdMapper;


    private boolean isSuperViewer() {
        PersonnelManagementDataSheets info = personnelManagementDataSheetsService.getByLoginUserId();
        return info != null && "黄改荣".equals(info.getFe1e());
    }

    /**
     * 奖惩记录列表
     *
     * @param param
     * @return
     */
    @GetMapping("/list")
    @Operation(description = "列表")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, Jx05dStaffIncentiveAndSanctionLo.class})
    ))
    public AjaxResult list(JcQueryDto param) {
        List<Jx05dStaffIncentiveAndSanctionLo> list = service.queryList(param);
        return Page.getDataTable(list);
    }

    /**
     * id查详情
     *
     * @param id
     * @return
     */
    @GetMapping("/getInfo/{id}")
    @Operation(description = "详情")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, Jx05dStaffIncentiveAndSanctionLo.class})
    ))
    public AjaxResult getInfo(@PathVariable("id") String id) {
        Jx05dStaffIncentiveAndSanctionLo info = service.getById(id);
        if (info == null) {
            return AjaxResult.error("记录不存在");
        }

        // 转换 theAuthor 字段
        String theAuthor = info.getTheAuthor();
        if (StringUtils.hasText(theAuthor)) {
            LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CorpMember::getMemberId, theAuthor).last("limit 1");
            CorpMember member = corpMemberMapper.selectOne(wrapper);
            if (member != null && StringUtils.hasText(member.getNick())) {
                info.setTheAuthor(member.getNick());
            }
        }

        // 转换 modifyer 字段
        String modifyer = info.getModifyer();
        if (StringUtils.hasText(modifyer)) {
            LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CorpMember::getMemberId, modifyer).last("limit 1");
            CorpMember member = corpMemberMapper.selectOne(wrapper);
            if (member != null && StringUtils.hasText(member.getNick())) {
                info.setModifyer(member.getNick());
            }
        }

        // 转换 approvingOfficer 字段
        String approvingOfficer = info.getApprovingOfficer();
        if (StringUtils.hasText(approvingOfficer)) {
            LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CorpMember::getMemberId, approvingOfficer).last("limit 1");
            CorpMember member = corpMemberMapper.selectOne(wrapper);
            if (member != null && StringUtils.hasText(member.getNick())) {
                info.setApprovingOfficer(member.getNick());
            }
        }

        return AjaxResult.success(info);
    }

    /**
     * 新增
     *
     * @param body
     * @return
     */
    @PostMapping("/save")
    @Operation(description = "新增")
    public AjaxResult save(@RequestBody Jx05dStaffIncentiveAndSanctionLo body) {
        boolean save = service.add(body);
        return AjaxResult.success(save);
    }

    /**
     * 编辑
     *
     * @param body
     * @return
     */
    @PostMapping("/update")
    @Operation(description = "编辑")
    public AjaxResult update(@RequestBody Jx05dStaffIncentiveAndSanctionLo body) {
        // 检查ID是否不为空
        if (body.getId() != null) {
            body.setStatus("待审核"); // 将状态改为待审核
        }
        boolean save = service.updateById(body);
        body.setWorkNumber("1");
        return AjaxResult.success(save);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @GetMapping("/remove/{id}")
    @Operation(description = "删除")
    public AjaxResult update(@PathVariable(value = "id") String id) {
        boolean save = service.removeById(id);
        return AjaxResult.success(save);
    }

    /**
     * 待审核列表
     *
     * @param param
     * @return
     */
    @GetMapping("/pending")
    @Operation(description = "待审核列表")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, Jx05dStaffIncentiveAndSanctionLo.class})
    ))
    public AjaxResult getPendingList(JcQueryDto param) {
        if (isSuperViewer()) {
            param.setType(2);
            param.setStatus("待审核");
            // 超级查看者不做车间限制
            List<Jx05dStaffIncentiveAndSanctionLo> list = service.queryList(param);
            return Page.getDataTable(list);
        }
        String workshop = getDirectorWorkshopOrNull();
        if (!StringUtils.hasText(workshop)) {
            return Page.getDataTable(new ArrayList<>());
//            return AjaxResult.success("无权限：仅准整主任或织布主任可访问");
        }
        param.setType(2); // 查看全部
        param.setStatus("待审核");
        param.setWorkshop(workshop);
        List<Jx05dStaffIncentiveAndSanctionLo> list = service.queryList(param);
        return Page.getDataTable(list);
    }

    /**
     * 已审核列表
     *
     * @param param
     * @return
     */
    @GetMapping("/approved")
    @Operation(description = "已审核列表")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, Jx05dStaffIncentiveAndSanctionLo.class})
    ))
    // 调试代码示例 - 在getApprovedList方法中添加日志
    public AjaxResult getApprovedList(JcQueryDto param) {
        log.info("原始参数: {}", param);

        if (isSuperViewer()) {
            log.info("用户是超级查看者");
            param.setType(2);
            param.setStatus("已审核");
            List<Jx05dStaffIncentiveAndSanctionLo> list = service.queryList(param);
            log.info("查询结果数量: {}", list.size());
            return Page.getDataTable(list);
        }

        String workshop = getDirectorWorkshopOrNull();
        log.info("用户车间权限: {}", workshop);
        if (!StringUtils.hasText(workshop)) {
            return Page.getDataTable(new ArrayList<>());
//            return AjaxResult.success("无权限：仅准整主任或织布主任可访问");
        }

        param.setType(2);
        param.setStatus("已审核");
        param.setWorkshop(workshop);
        log.info("设置后参数: {}", param);

        String userId = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CorpMember::getUserId, userId).last("limit 1");
        CorpMember cm = corpMemberMapper.selectOne(wrapper);
        log.info("用户成员信息: {}", cm);

        if (cm == null) {
            return AjaxResult.error("当前账户未绑定成员信息");
        }

        param.setApprovingOfficer(cm.getMemberId());
        log.info("最终参数: {}", param);

        List<Jx05dStaffIncentiveAndSanctionLo> list = service.queryList(param);
        log.info("查询结果数量: {}", list.size());
        return Page.getDataTable(list);
    }

    /**
     * 审核奖惩单
     *
     * @param request
     * @return
     */
    @PostMapping("/approve")
    @Operation(description = "审核奖惩单（支持单个或批量）")
    public AjaxResult approve(@RequestBody ApproveRequest request) {
        List<String> ids = request.getIds(); // 从对象中获取ids
        String workshop = getDirectorWorkshopOrNull();
        if (ids == null || ids.isEmpty()) {
            return AjaxResult.error("请选择要审核的奖惩单");
        }
        if (!StringUtils.hasText(workshop)) {
            return AjaxResult.error("无权限：仅部门主管可审核");
//            return AjaxResult.error("无权限：仅准整主任或织布主任可审核");
        }
        List<Jx05dStaffIncentiveAndSanctionLo> records = service.listByIds(ids);
        boolean sameWorkshop = records.stream().allMatch(r -> workshop.equals(r.getWorkshop()));
        if (!sameWorkshop) {
            return AjaxResult.error("所选单据包含其他车间，无法审核");
        }
        boolean success = service.approve(ids);
        return success ? AjaxResult.success("审核成功") : AjaxResult.error("审核失败");
    }

    /**
     * 作废奖惩单
     *
     * @param request
     * @return
     */
    @PostMapping("/invalidate")
    @Operation(description = "作废奖惩单（支持单个或批量）")
    public AjaxResult invalidate(@RequestBody ApproveRequest request) {
        List<String> ids = request.getIds(); // 从对象中获取ids
        String workshop = getDirectorWorkshopOrNull();

        if (ids == null || ids.isEmpty()) {
            return AjaxResult.error("请选择要审核的奖惩单");
        }
        if (!StringUtils.hasText(workshop)) {
            return AjaxResult.error("无权限：仅部门主管可审核");
//            return AjaxResult.error("无权限：仅准整主任或织布主任可审核");
        }

        List<Jx05dStaffIncentiveAndSanctionLo> records = service.listByIds(ids);
        boolean sameWorkshop = records.stream().allMatch(r -> workshop.equals(r.getWorkshop()));
        if (!sameWorkshop) {
            return AjaxResult.error("所选单据包含其他车间，无法审核");
        }

        boolean success = service.invalidate(ids);
        return success ? AjaxResult.success("作废成功") : AjaxResult.error("作废失败");
    }

    /**
     * 当前登录人奖惩记录统计
     *
     * @return
     */
    @GetMapping("/statistics")
    @Operation(description = "当前登录人奖惩记录统计")
    public AjaxResult getStatistics() {
        try {
            Map<String, Object> statistics = service.getCurrentUserStatistics();
            return AjaxResult.success("查询成功", statistics);
        } catch (Exception e) {
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 奖惩统计 - 总体统计
     *
     * @param startDate 开始日期 (格式: yyyy-MM-dd)
     * @param endDate   结束日期 (格式: yyyy-MM-dd)
     * @return
     */
    @GetMapping("/statistics/overview")
    @Operation(description = "奖惩统计 - 总体统计")
    public AjaxResult getStatisticsOverview(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            Map<String, Object> overview = service.getStatisticsOverview(startDate, endDate);
            return AjaxResult.success("查询成功", overview);
        } catch (Exception e) {
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 奖惩统计 - 车间统计
     *
     * @param startDate 开始日期 (格式: yyyy-MM-dd)
     * @param endDate   结束日期 (格式: yyyy-MM-dd)
     * @return
     */
    @GetMapping("/statistics/workshop")
    @Operation(description = "奖惩统计 - 车间统计")
    public AjaxResult getWorkshopStatistics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            List<Map<String, Object>> workshopStats = service.getWorkshopStatistics(startDate, endDate);
            return AjaxResult.success("查询成功", workshopStats);
        } catch (Exception e) {
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 奖惩统计 - 班组统计
     *
     * @param startDate 开始日期 (格式: yyyy-MM-dd)
     * @param endDate   结束日期 (格式: yyyy-MM-dd)
     * @return
     */
    @GetMapping("/statistics/team")
    @Operation(description = "奖惩统计 - 班组统计")
    public AjaxResult getTeamStatistics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            List<Map<String, Object>> teamStats = service.getTeamStatistics(startDate, endDate);
            return AjaxResult.success("查询成功", teamStats);
        } catch (Exception e) {
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 奖惩统计 - 员工统计
     *
     * @param startDate 开始日期 (格式: yyyy-MM-dd)
     * @param endDate   结束日期 (格式: yyyy-MM-dd)
     * @return
     */
    @GetMapping("/statistics/employee")
    @Operation(description = "奖惩统计 - 员工统计")
    public AjaxResult getEmployeeStatistics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            List<Map<String, Object>> employeeStats = service.getEmployeeStatistics(startDate, endDate);
            return AjaxResult.success("查询成功", employeeStats);
        } catch (Exception e) {
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }


    private String getDirectorWorkshopOrNull() {
        PersonnelManagementDataSheets info = personnelManagementDataSheetsService.getByLoginUserId();
        if (info == null) return null;
        String sector = info.getSector();
        String fe1e = info.getFe1e();
        String headsbm = bcry11ygsqbdMapper.selectDepartmentZg(sector);
        return StringUtils.hasText(headsbm) && headsbm.equals(fe1e) ? sector : null;
//        String position = info.getPositions1();
//        if ("准整主任".equals(position) || "织布主任".equals(position)) {
//            return info.getSector();
//        }
//        return null;
    }

}
